const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
const axios = require('axios');
class ChatController extends Controller {
  // 新增agent接口
  async addChatData() {
    const { ctx } = this;
    const text = ctx.request.body.text;
    const title = text.length > 10 ? text.slice(0, 10) : text;
    const timestamp = Date.now();
    const content = [{
      type: 0,
      text,
      timestamp
    }];

    const response = await axios.post('https://spark-api-open.xf-yun.com/v1/chat/completions', {
      model: 'lite',
      "messages": [
        {
          "role": "user",
          "content": text
        }
      ],
      "stream": false
    }, {
      headers: {
        "Authorization": "Bearer EqUmcARNdMeYAyknGUDe:tUSDqwOBAOiFSkdUCAjb"
      }
    })

    content.push({
      type: 1,
      text: response.data.choices[0].message.content,
      timestamp: Date.now()
    })

    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const res = await this.ctx.model.User.findOne({ _id: decoded.id });

    try {
      const result = await ctx.model.Chat.create({ title, content, date: timestamp, userId: res._id, type: 0 });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 通过id获取聊天详情接口
  async getChatDetailById() {
    const { ctx } = this;
    const id = ctx.query.id;
    console.log(id)
    try {
      const result = await ctx.model.Chat.findById(id);
      if (result) {
        ctx.body = { success: true, data: result };
      } else {
        ctx.body = { success: false, error: '未找到对应的聊天记录' };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 新增另一个消息记录添加接口
  async addNewChatData() {
    const { ctx } = this;
    const { text, id } = ctx.request.body;
    try {
      const chatDetail = await ctx.model.Chat.findById(id);
      if (chatDetail) {
        const content = chatDetail.content;
        const timestamp = Date.now();
        content.push({
          type: 0,
          text,
          timestamp
        })

        const response = await axios.post('https://spark-api-open.xf-yun.com/v1/chat/completions', {
          model: 'lite',
          "messages": [
            {
              "role": "user",
              "content": text
            }
          ],
          "stream": false
        }, {
          headers: {
            "Authorization": "Bearer EqUmcARNdMeYAyknGUDe:tUSDqwOBAOiFSkdUCAjb"
          }
        })

        content.push({
          type: 1,
          text: response.data.choices[0].message.content,
          timestamp: Date.now()
        })

        try {
          await ctx.model.Chat.findByIdAndUpdate(id, { content, date: timestamp });
          ctx.body = { success: true, message: '聊天记录更新成功' };
        } catch (error) {
          ctx.body = { success: false, error: error.message };
        }
      } else {
        console.log('未找到对应的聊天记录');
      }
    } catch (error) {
      console.error('查询聊天记录时出错:', error);
    }
  }
  // 返回当前用户所有聊天记录接口
  async getAllChatsByUser() {
    const { ctx } = this;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Chat.find({ userId: decoded.id }).select('title date _id').sort({ date: -1 });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  // 返回当前用户所有聊天记录详情接口
  async getAllChatsByUser2() {
    const { ctx } = this;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Chat.find({ userId: decoded.id }).sort({ date: -1 });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 修改title字段的接口
  async updateTitle() {
    const { ctx } = this;
    const { id, title } = ctx.request.body;
    try {
      const result = await ctx.model.Chat.findByIdAndUpdate(id, { title: title }, { new: true });
      if (result) {
        ctx.body = { success: true, message: '标题更新成功', data: result };
      } else {
        ctx.body = { success: false, error: '未找到对应的聊天记录' };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 通过title搜索列表数据接口
  async searchChatsByTitle() {
    const { ctx } = this;
    const { title } = ctx.request.body;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const regex = new RegExp(title, 'i');
      const result = await ctx.model.Chat.find({ userId: decoded.id, title: regex }).select('title date _id').sort({ date: -1 });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  // 通过id删除对话接口
  async deleteChatById() {
    const { ctx } = this;
    const id = ctx.params.id;
    try {
      const result = await ctx.model.Chat.findByIdAndDelete(id);
      if (result) {
        ctx.body = { success: true, message: '对话记录删除成功' };
      } else {
        ctx.body = { success: false, error: '未找到对应的聊天记录' };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 添加数据到collect表的接口
  async addToCollect() {
    const { ctx } = this;
    const data = ctx.request.body;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Collect.create({
        ...data,
        date: Date.now(),
        userId: decoded.id,
        chatId: data.id
      });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  // 收藏添加笔记接口
  async addCommentToCollect() {
    const { ctx } = this;
    const { id, comment } = ctx.request.body;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", { signed: false, encrypt: true });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Collect.findByIdAndUpdate(
        id,
        { $push: { comments: comment } },
        { new: true }
      );
      if (result) {
        ctx.body = { success: true, message: '评论添加成功', data: result };
      } else {
        ctx.body = { success: false, error: '未找到对应的收藏数据' };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 获取我的收藏数据接口
  async getMyCollectData() {
    const { ctx } = this;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Collect.find({ userId: decoded.id }).sort({ date: -1 });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 根据id删除一条收藏数据接口
  async deleteCollectById() {
    const { ctx } = this;
    const id = ctx.params.id;
    try {
      const result = await ctx.model.Collect.findByIdAndDelete(id);
      if (result) {
        ctx.body = { success: true, message: '收藏数据删除成功' };
      } else {
        ctx.body = { success: false, error: '未找到对应的收藏数据' };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 根据id获取一条收藏数据接口
  async getCollectDataById() {
    const { ctx } = this;
    const id = ctx.params.id;
    try {
      const result = await ctx.model.Collect.findById(id);
      if (result) {
        ctx.body = { success: true, data: result };
      } else {
        ctx.body = { success: false, error: '未找到对应的收藏数据' };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 根据关键词搜索收藏内容的接口
  async searchCollectByKeyword() {
    const { ctx } = this;
    const { keyword } = ctx.request.query;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const regex = new RegExp(keyword, 'i');
      const result = await ctx.model.Collect.find({ userId: decoded.id, $or: [{ title: regex }, { content: regex }] }).sort({ date: -1 });
      ctx.body = { success: true, data: result };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  // 新闻
  async searchNews() {
    const { ctx } = this;
    const { keyword } = ctx.request.query;
    try {

      // 获取当前用户id
      const token = this.ctx.cookies.get("token", {
        signed: false,
        encrypt: true
      });
      const decoded = jwt.verify(token, "aaa");
      const result = await ctx.model.Menu.find({ userId: decoded.id });

      // if (result.length == 0) {
      //   const res = await axios.get('https://whyta.cn/api/tx/guonei?key=36de5db81215&rand=1')

      //   ctx.body = {
      //     success: true,
      //     data: res.data.result.newslist
      //   }
      // } else {
      //   let a = []
      //   for (let i = 0; i < result[0].menus.length; i++) {
      //     let word = '&word=' + result[0].menus[i]
      //     console.log('====', word)
      //     await new Promise(resolve => setTimeout(resolve, 1000));
      //     const res = await axios.get('https://whyta.cn/api/tx/guonei?key=36de5db81215&rand=1' + word)

      //     a = a.concat(res.data.result.newslist)
      //   }

      //   ctx.body = {
      //     success: true,
      //     data: a
      //   }
      // }

      // const res = await axios.get('https://whyta.cn/api/tx/guonei?key=36de5db81215&rand=1')
      ctx.body = {
        success: true,
        data: [{
          title: "吉利汽车拟收购极氪全部股份，极氪将私有化并与吉利汽车合并",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/qt_01.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749260143&x-signature=RhRhI54sPgEBBcty3Ci2%2FLuPyuE%3D',
          ctime: '2025-05-07',
        }, {
          title: "沃尔沃发布全新SMA超级混动架构及首款车型XC70，预计售价40-50万",
          picUrl: 'https://p3-fpa-news-img-sign.byteimg.com/tos-cn-i-s674jgotk9/fb58af2aeb5a4b1ebcd270048de4264a~tplv-s674jgotk9-image.jpeg?rk3s=4cf38c59&x-expires=1747272943&x-signature=%2B4xz69FUct6orIDNA4bLS2e4PA4%3D',
          ctime: '2025-05-07',
        }, {
          title: "苹果高管埃迪·库伊：AI发展迅猛，iPhone未来10年内或被淘汰",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/qt_02.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749260143&x-signature=40JuV%2FpIiRVfgd%2FyQ1yG6r8P2n8%3D',
          ctime: '2025-05-07',
        }, {
          title: "腾讯优化DeepSeek开源的DeepEP通信框架，性能提升获对方致谢，已开源",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/kj_01.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749260143&x-signature=0KmI4xuVtB7H2qvpRhsH4w455d8%3D',
          ctime: '2025-05-07',
        }, {
          title: "理想汽车CEO李想谈特斯拉FSD：12.5版本前距真实能力差距大，13.0以后能力强，车企应扎实练基本功",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/qt_03_1.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749260143&x-signature=ui6SJrImZKcLrtS7ZLgQFde0KYw%3D',
          ctime: '2025-05-07',
        }, {
          title: "淘宝天猫与小红书达成战略合作，打造“红猫计划”打通种草到购买全链路",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/qt_04.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749260143&x-signature=hW2VCqOaxLzzNJgdWb512%2FT2%2FQI%3D',
          ctime: '2025-05-06',
        }, {
          title: "中国常驻联合国副代表耿爽：驳斥美方指责抹黑，敦促停止搞指责外交",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/ss_01.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749279202&x-signature=sES7uP6sldG0k3PoJJDlR21kupE%3D',
          ctime: '2025-05-06',
        }, {
          title: "中国出台货币宽松政策并启动中美贸易谈判，四大投行多维解析",
          picUrl: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/cj_05.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=6823e3d0&x-expires=1749279202&x-signature=YTfq6v6u4KyI1New5foCtkyXIkY%3D',
          ctime: '2025-05-06',
        }]
      }
    }
    catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async menus() {
    const { ctx } = this;
    const { keyword } = ctx.request.query;
    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    try {
      const result = await ctx.model.Menu.find({ userId: decoded.id });
      if (result.length == 0) {
        ctx.body = {
          success: true,
          data: ['科技', '生活', '体育', '娱乐', '军事', '教育', '财经', '汽车', '游戏', '旅游'].map((item) => {
            return {
              name: item,
              checked: false
            }
          })
        };
      } else {
        ctx.body = {
          success: true,
          data: ['科技', '生活', '体育', '娱乐', '军事', '教育', '财经', '汽车', '游戏', '旅游'].map((item) => {
            if (result[0].menus.includes(item)) {
              return {
                name: item,
                checked: true
              }
            } else {
              return {
                name: item,
                checked: false
              }
            }
          })
        };
      }

    }
    catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  async saveMenus() {
    const { ctx } = this;
    const { menus } = ctx.request.body;

    // 获取当前用户id
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");

    try {
      // 查询当前用户在menu表中是否有记录
      const existingMenu = await ctx.model.Menu.findOne({ userId: decoded.id });
      if (existingMenu) {
        // 如果有记录，更新数据
        existingMenu.menus = menus;
        const result = await existingMenu.save();
        ctx.body = { success: true, data: result };
      } else {
        // 如果没有记录，新增数据
        const result = await ctx.model.Menu.create({ menus, userId: decoded.id });
        ctx.body = { success: true, data: result };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
}

// 导出时确保包含新的方法
module.exports = ChatController;